package com.rc.saas.tenant.controller.channel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.mq.MqConfig;
import com.rc.saas.tenant.common.mq.MqProducer;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.channel.RcChannelApply;
import com.rc.saas.tenant.model.enterprise.EnterpriseMember;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.member.RcMemberFlag;
import com.rc.saas.tenant.model.tenant.TenantRole;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.tenant.TenantRoleSearch;
import com.rc.saas.tenant.service.channel.RcChannelApplyService;
import com.rc.saas.tenant.service.enterprise.EnterpriseMemberService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.member.RcMemberFlagService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.vo.channel.RcChannelApplyVo;
import com.rc.saas.tenant.vo.member.MemberResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/channel/apply")
public class ChannelApplyContorller {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RcChannelApplyService channelApplyService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private EnterpriseMemberService enterpriseMemberService;

    @Autowired
    private RcMemberFlagService memberFlagService;

    @Autowired
    private MqProducer mqProducer;

    @RequestMapping("/index")
    public String index() {
        return "/templates/channel/channel";
    }

    @ResponseBody
    @RequestMapping("/listPageChannelApply")
    public WebPageInfo listPageChannelApply(Long enterpriseId, String channelName, Integer pageNo, Integer pageSize) {
        PageInfo<RcChannelApplyVo> pageInfo = channelApplyService.listPageChannelApply(enterpriseId, channelName, pageNo, pageSize);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 导出渠道商列表
     */
    @ResponseBody
    @RequestMapping(value = "/export", method = RequestMethod.GET)
    public TResponse export(Long enterpriseId, String channelName,
                            @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
                            @RequestParam(value = "pageSize",defaultValue = "1000") Integer pageSize, HttpServletResponse response) {
        try {
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            PageInfo<RcChannelApplyVo> pageInfo = channelApplyService.listPageChannelApply(enterpriseId, channelName, pageNo, pageSize);
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("渠道商列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), RcChannelApplyVo.class).sheet("渠道商列表").doWrite(pageInfo.getList());
            return null;
        } catch (Exception e) {
            logger.error("导出渠道商列表失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }

    @ResponseBody
    @RequestMapping("/updateChannelApplyForAudit")
    public TResponse updateChannelApplyForAudit(Long id, String status, String remark) {
        channelApplyService.updateChannelApplyForAudit(id, status, remark);
        return TResponse.SUCCESS();
    }

    @RequestMapping("/add")
    public String add(Model model) {
        TenantUser user = ShiroUtils.getSessionUser();
        List<EnterpriseMember> list = enterpriseMemberService.selectEnterpriseMembers(user.getTenantCode());
        model.addAttribute("enterpriseList", list);
        return "/templates/channel/addChannel";
    }

    @RequestMapping("/edit/{id}")
    public String edit(Model model, @PathVariable("id") Long id) {
        RcChannelApply channelApply = channelApplyService.selectByPrimaryKey(id);
        model.addAttribute("channelApply",channelApply);
        /*MemberResultVo member = memberInfoService.selectMemberById(channelApply.getMemberId());
        model.addAttribute("member",member);*/
        TenantUser user = ShiroUtils.getSessionUser();
        List<EnterpriseMember> list = enterpriseMemberService.selectEnterpriseMembers(user.getTenantCode());
        model.addAttribute("enterpriseList", list);
        return "/templates/channel/editChannel";
    }

    @RequestMapping("/detail/{id}")
    public String detail(Model model, @PathVariable("id") Long id) {
        RcChannelApply channelApply = channelApplyService.selectByPrimaryKey(id);
        MemberInfo memberInfo = memberInfoService.selectByPrimaryKey(channelApply.getMemberId());
        //设置昵称
        if (StringUtil.isBlank(memberInfo.getNickname())){
            memberInfo.setNickname(memberInfo.getNickname2());
        }
        /*MemberResultVo member = memberInfoService.selectMemberById(channelApply.getMemberId());
        model.addAttribute("member",member);*/
        EnterpriseMember enterprise = enterpriseMemberService.selectByPrimaryKey(channelApply.getEnterpriseId());
        RcMemberFlag memberFlag = memberFlagService.selectByPrimaryKey(channelApply.getMemberId());
        model.addAttribute("channelApply",channelApply);
        model.addAttribute("memberInfo",memberInfo);
        model.addAttribute("enterprise",enterprise);
        if (memberFlag == null) {
            memberFlag = new RcMemberFlag();
        }
        model.addAttribute("channelLevel", memberFlag.getChannelLevel());
        return "/templates/channel/detailChannel";
    }

    @ResponseBody
    @RequestMapping("/addChannelApply")
    public TResponse addChannelApply(RcChannelApply channelApply) {
        channelApplyService.insertReturnId(channelApply);
        Map<String, Long> map = new HashMap<>();
        map.put("channelApplyId", channelApply.getChannelApplyId());
        mqProducer.send(MqConfig.platform_apply, JSON.toJSONString(map), 1);

        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping("/updateChannelApply")
    public TResponse updateChannelApply(RcChannelApply channelApply) {
        try {
            channelApplyService.updateEnterpriseId(channelApply);
        } catch (Exception e){
            return TResponse.FAIL("更新企业失败");
        }
        return TResponse.SUCCESS();
    }

    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public TResponse delChannelApply(Long id) {
        channelApplyService.deleteChannelApply(id);
        return TResponse.SUCCESS();
    }
}
